<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div v-if="!route.query?.id">新增封面生产单</div>
            <div v-else-if="route.query?.copy">复制封面生产单</div>
            <div v-else-if="route.query?.info">
              封面生产单详情
              <el-tag>{{ form.produceNo }}</el-tag>
            </div>
            <div v-else>编辑封面生产单</div>
          </div>
        </template>
        <template #extra>
          <!--  -->
          <div class="flex items-center" v-if="!route.query.info">
            <el-button type="primary" @click="submitForm">保 存</el-button>
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item title="基本信息" disabled name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              ref="userRef"
              label-width="120px"
            >
              <el-row :gutter="20">
                <!-- <el-form-item label="新/旧版" prop="isNew">
                                        <el-select
                                            style="width: 100%"
                                            v-model="form.isNew"
                                            placeholder="请选择"
                                        >
                                            <el-option
                                                v-for="item in ems_produce_is_new"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                    </el-form-item> -->
                <el-col :span="8">
                  <el-form-item label="出版编号" prop="pubNo">
                    <el-input
                      v-model="form.pubNo"
                      @change="changePubNo"
                      :disabled="flag"
                      :validate-event="false"
                      maxlength="20"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="下单日期" prop="submitDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.submitDate"
                      value-format="YYYY-MM-DD"
                      @change="submitDateChange"
                      :disabled="flag"
                      type="date"
                      placeholder="请选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="交货日期" prop="deliverDate">
                    <el-date-picker
                      style="width: 100%"
                      :disabled="flag"
                      v-model="form.deliverDate"
                      value-format="YYYY-MM-DD "
                      type="date"
                      placeholder="请选择日期"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <!-- <el-col :span="8">
                                    <el-form-item label="文件日期" prop="fileDate">
                                        <el-date-picker
                                            style="width: 100%"
                                            :disabled="flag"
                                            v-model="form.fileDate"
                                            value-format="YYYY-MM-DD "
                                            type="date"
                                            placeholder="请选择日期"
                                        />
                                    </el-form-item>
                                </el-col>-->
                <!-- <el-col :span="8">
                                    <el-form-item label="打包要求" prop="packageRequire">
                                        <el-select
                                            style="width: 100%"
                                            v-model="form.packageRequire"
                                            :disabled="flag"
                                            placeholder="请选择"
                                        >
                                            <el-option
                                                v-for="item in ems_produce_package_require"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-col>-->
                <el-col :span="8">
                  <el-form-item label="车间" prop="workshopId">
                    <el-select
                      :disabled="flag"
                      style="width: 100%"
                      v-model="form.workshopId"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in cover_workshop"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                                    <el-form-item label="加急交货日期" prop="urgentDate">
                                        <el-date-picker style="width: 100%; " v-model="form.urgentDate"
                                            format="YYYY-MM-DD HH:mm:ss" date-format="MMM DD, YYYY" time-format="HH:mm"
                                            type="datetime" placeholder="请选择时间" />
                                    </el-form-item>
                                </el-col> -->
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item title="产品信息" disabled name="2">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">产品信息</span>
          </template>
          <div class="order-form">
            <el-button
              size="small"
              type="primary"
              style="margin-bottom: 10px"
              v-if="!route.query.info"
              @click="handleAddProduceProduct"
            >
              选择产品
            </el-button>
            <el-form
              :model="data"
              ref="produceProductListForm"
              :disabled="flag"
              class="data-form"
            >
              <el-table
                :data="data.produceProductList"
                border
                :header-cell-class-name="must"
              >
                <!-- <el-table-column type="selection" width="55" /> -->
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />
                <el-table-column
                  label="产品序列号"
                  v-if="route.query?.id && !copy"
                  min-width="120"
                  prop="productNo"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="订单数量"
                  width="120"
                  prop="produceCount"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="
                        'produceProductList.' + scope.$index + '.produceCount'
                      "
                      :rules="[
                        {
                          required: true,
                          message: '订单数量',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        type="number"
                        @blur="changeProduceCount(scope.row)"
                        @mousewheel.prevent
                        v-model="scope.row.produceCount"
                        placeholder="请输入订单数量"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="书刊编码"
                  min-width="120"
                  prop="bookCode"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="书刊名称"
                  min-width="160"
                  prop="bookName"
                  align="center"
                ></el-table-column>
                <!-- <el-table-column
                                    label="是否做版"
                                    prop="newPast"
                                    min-width="120"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <el-form-item
                                            :prop="
                                                'produceProductList.' + scope.$index + '.newPast'
                                            "
                                            :rules="[
                                                {
                                                    required: true,
                                                    message: '是否做版',
                                                    trigger: 'blur',
                                                },
                                            ]"
                                        >
                                            <el-select
                                                clearable
                                                style="width: 100%"
                                                v-model="scope.row.newPast"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="item in ems_produce_new_past"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </el-select>
                                        </el-form-item>
                                    </template>
                                </el-table-column> -->
                <!-- <el-table-column
                                    label="出版编号"
                                    min-width="120"
                                    prop="pubNo"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <el-form-item>
                                            <el-input
                                                v-model="scope.row.pubNo"
                                                placeholder="请输入出版编号"
                                            ></el-input>
                                        </el-form-item>
                                    </template>
                                </el-table-column> -->
                <el-table-column
                  label="产品品种"
                  prop="breedType"
                  min-width="120"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="清样编号"
                  min-width="120"
                  prop="sampleNo"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        v-model="scope.row.sampleNo"
                        placeholder="请输入清样编号"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="文件号"
                  min-width="120"
                  prop="fileNo"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        v-model="scope.row.fileNo"
                        placeholder="请输入文件号"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="书号"
                  min-width="120"
                  prop="bookNo"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="定价"
                  min-width="120"
                  prop="fixPrice"
                  align="center"
                >
                  <template #default="scope">
                    <el-input
                      type="number"
                      @mousewheel.prevent
                      v-model="scope.row.fixPrice"
                      placeholder="请输入定价"
                    />
                  </template>
                </el-table-column>
                <!-- <el-table-column label="交货日期" min-width="120" prop="deliverDate" align="center">
                                    <template v-slot="{ row }">
                                        {{ row.deliverDate?.split('T')[0] ?? '' }}
                                    </template>
                                </el-table-column> -->
                <el-table-column
                  label="组成"
                  min-width="120"
                  prop="composition"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="ems_order_make_up_fm"
                      :value="scope.row.composition"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="印色"
                  min-width="100"
                  prop="printColor"
                  align="center"
                >
                  <template #default="scope">
                    <!-- <dict-tag
                                            :options="ems_order_print_color"
                                            :value="scope.row.printColor"
                                        /> -->
                    <el-select
                      @blur="changePrintColor(scope.row)"
                      clearable
                      style="width: 100%"
                      v-model="scope.row.printColor"
                      placeholder="请选择印色"
                    >
                      <el-option
                        v-for="item in ems_order_print_color"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="颜色"
                  width="130"
                  prop="color"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'produceProductList.' + scope.$index + '.color'"
                      :rules="[
                        {
                          required: true,
                          message: '颜色',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-select
                        clearable
                        style="width: 100%"
                        v-model="scope.row.color"
                        placeholder="请选择颜色"
                      >
                        <el-option
                          v-for="item in ems_produce_color"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="纸型"
                  width="120"
                  prop="paperType"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-select
                        style="width: 100%"
                        v-model="scope.row.paperType"
                        placeholder="请选择纸型"
                        :disabled="flag"
                      >
                        <el-option
                          v-for="item in mes_paper_type"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                  <!-- <template #default="scope">
                                        <dict-tag
                                            :options="mes_paper_type"
                                            :value="scope.row.paperType"
                                        />
                                    </template> -->
                </el-table-column>
                <el-table-column
                  label="纸张编码"
                  width="120"
                  prop="paperNo"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'produceProductList.' + scope.$index + '.paperNo'"
                      :rules="[
                        {
                          required: true,
                          message: '纸张编码',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        v-model="scope.row.paperNo"
                        readonly
                        @click="openPaperDialog(scope.row, scope.$index)"
                        placeholder="请选择纸张编码"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

                <!--<el-table-column
                                    label="用纸尺寸"
                                    prop="paperSize"
                                    width="120"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <el-form-item
                                            :prop="
                                                'produceProductList.' + scope.$index + '.paperSize'
                                            "
                                            :rules="[
                                                {
                                                    required: true,
                                                    message: '用纸尺寸',
                                                    trigger: 'blur',
                                                },
                                            ]"
                                        >
                                            <el-select
                                                clearable
                                                style="width: 100%"
                                                v-model="scope.row.paperSize"
                                                placeholder="请选择用纸尺寸"
                                            >
                                                <el-option
                                                    v-for="item in ems_produce_paper_size"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </el-select>
                                        </el-form-item>
                                    </template>
                                </el-table-column>-->

                <el-table-column
                  label="纸张名称"
                  width="120"
                  prop="paperName"
                  align="center"
                />
                <!-- <el-table-column label="订单数量" width="120" prop="orderAmount" align="center">
                                </el-table-column> -->
                <el-table-column
                  label="覆膜"
                  width="120"
                  prop="coverFilm"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-select
                        clearable
                        style="width: 100%"
                        @blur="changeCoverFilm(scope.row)"
                        v-model="scope.row.coverFilm"
                        placeholder="请选择"
                      >
                        <el-option
                          v-for="item in ems_produce_cover_film"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  label="喷码"
                  width="100"
                  prop="marking"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-select
                        clearable
                        style="width: 100%"
                        v-model="scope.row.marking"
                        placeholder="请选择喷码"
                      >
                        <el-option
                          v-for="item in ems_produce_marking"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="联版数量"
                  width="120"
                  prop="lianbanCount"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        type="number"
                        @mousewheel.prevent
                        @blur="changeProduceCount(scope.row)"
                        v-model="scope.row.lianbanCount"
                        placeholder="请输入联版数量"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="内文承印厂"
                  width="120"
                  prop="textPrinter"
                  align="center"
                >
                  <template #default="scope">
                    <el-autocomplete
                      v-model="scope.row.textPrinter"
                      :fetch-suggestions="querySearch"
                      clearable
                      style="width: 100%"
                      class="inline-input w-50"
                      placeholder="请选择或者输入"
                      @select="handleSelect"
                    />
                    <!-- <el-select
                                            clearable
                                            style="width: 100%"
                                            v-model="scope.row.textPrinter"
                                            placeholder="请选择内文承印厂"
                                        >
                                            <el-option
                                                v-for="item in produce_text_printer"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select> -->
                    <!-- <el-form-item>
                                            <el-input
                                                v-model="scope.row.textPrinter"
                                                placeholder="请输入内文承印厂"
                                            ></el-input>
                                        </el-form-item> -->
                  </template>
                </el-table-column>
                <!--<el-table-column
                                    label="客户名称"
                                    width="120"
                                    prop="customerName"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <el-form-item>
                                            <el-input
                                                v-model="scope.row.customerName"
                                                placeholder="请输入客户名称"
                                            ></el-input>
                                        </el-form-item>
                                    </template>
                                </el-table-column>-->
                <el-table-column
                  label="科目"
                  width="100"
                  prop="subjectType"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="ems_workshop_subject_type"
                      :value="scope.row.subjectType"
                    />
                  </template>
                </el-table-column>

                <el-table-column
                  label="操作"
                  v-if="!route.query.info"
                  align="center"
                  fixed="right"
                  class-name="small-padding fixed-width"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleDelete(scope.row)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item title="纸张信息" disabled name="3">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">纸张信息</span>
          </template>
          <div class="order-form">
            <el-form
              :model="data"
              ref="producePaperListForm"
              :disabled="flag"
              class="data-form"
            >
              <el-table
                :data="data.producePaperList"
                ref="producePaperListRef"
                border
                :row-class-name="tableRowClassName"
              >
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />
                <el-table-column
                  v-if="route.query?.id && !copy"
                  label="纸张序列号"
                  min-width="120"
                  prop="paperProduceNo"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="纸张编码"
                  min-width="120"
                  prop="paperNo"
                  align="center"
                ></el-table-column>

                <el-table-column
                  label="纸张类型"
                  prop="type"
                  width="120"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'producePaperList.' + scope.$index + '.type'"
                      :rules="[
                        {
                          required: true,
                          message: '纸张类型',
                          trigger: 'change',
                        },
                      ]"
                    >
                      <el-select
                        clearable
                        style="width: 100%"
                        v-model="scope.row.type"
                        placeholder="请选择纸张类型"
                      >
                        <el-option
                          v-for="item in mes_paper_material"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="纸张名称"
                  width="120"
                  prop="paperName"
                  align="center"
                />
                <el-table-column
                  label="纸型"
                  min-width="120"
                  prop="paperType"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_type"
                      :value="scope.row.paperType"
                    />
                  </template>
                </el-table-column>
                <!-- <el-table-column label="品种" min-width="120" prop="brand" align="center">
                                    <template #default="scope">
                                        <dict-tag :options="ems_order_breed_type" :value="scope.row.brand" />
                                    </template>
                                </el-table-column> -->
                <el-table-column
                  label="定量"
                  min-width="120"
                  prop="weight"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="规格"
                  min-width="120"
                  prop="specifications"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_specs"
                      :value="scope.row.specifications"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="幅宽(mm)"
                  min-width="120"
                  prop="length"
                  align="center"
                ></el-table-column>
                <!-- <el-table-column
                                    label="宽度(mm)"
                                    min-width="120"
                                    prop="width"
                                    align="center"
                                ></el-table-column> -->
                <el-table-column
                  label="单位"
                  min-width="120"
                  prop="unit"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_unit"
                      :value="scope.row.unit"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="库存数量"
                  min-width="120"
                  prop="amount"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="数量"
                  min-width="120"
                  prop="reamAmount"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="裁切尺寸"
                  width="120"
                  prop="size"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        v-model="scope.row.size"
                        placeholder="请输入裁切尺寸"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item title="印刷管理" disabled name="4">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">印刷管理</span>
          </template>
          <div class="order-form">
            <el-form :model="data" ref="producePrintListForm" class="data-form">
              <!-- :disabled="flag"-->
              <el-table
                :data="data.producePrintList"
                ref="producePrintListRef"
                border
                :header-cell-class-name="mustPrint"
                :row-class-name="tableRowClassName"
              >
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />
                <el-table-column
                  v-if="route.query?.id && !copy"
                  label="印刷序列号"
                  min-width="120"
                  prop="printProduceNo"
                  align="center"
                ></el-table-column>
                <!-- <el-table-column
                                    label="书刊编码"
                                    min-width="120"
                                    prop="bookNo"
                                    align="center"
                                ></el-table-column>
                                <el-table-column
                                    label="书刊名称"
                                    min-width="160"
                                    prop="bookName"
                                    align="center"
                                ></el-table-column> -->
                <!-- <el-table-column
                                    label="组成"
                                    min-width="120"
                                    prop="composition"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <dict-tag
                                            :options="ems_order_make_up_fm"
                                            :value="scope.row.composition"
                                        />
                                    </template>
                                </el-table-column> -->
                <el-table-column
                  label="纸型"
                  width="100"
                  prop="paperType"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_type"
                      :value="scope.row.paperType"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="定量"
                  width="60"
                  prop="weight"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="印数"
                  width="100"
                  prop="printAmount"
                  align="center"
                >
                  <template #default="scope">
                    <el-input
                      type="number"
                      @mousewheel.prevent
                      @blur="changePrintAmount(scope.row, scope.$index)"
                      v-model="scope.row.printAmount"
                      :disabled="flag"
                      placeholder="请输入印数"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  label="用纸令数"
                  width="80"
                  prop="reamAmount"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="损耗系数(%)"
                  width="100"
                  prop="lossCoefficient"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        :disabled="flag"
                        type="number"
                        @mousewheel.prevent
                        @blur="changeLossCoefficient(scope.row, scope.$index)"
                        v-model="scope.row.lossCoefficient"
                        placeholder="请输入损耗系数"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="损耗令数"
                  width="80"
                  prop="lossReam"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="用纸总令数"
                  width="90"
                  prop="totalReamAmount"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="版材尺寸"
                  prop="sheetSize"
                  width="140"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'producePrintList.' + scope.$index + '.sheetSize'"
                      :rules="[
                        {
                          required: true,
                          message: '版材尺寸',
                          trigger: 'change',
                        },
                      ]"
                    >
                      <el-select
                        clearable
                        style="width: 100%"
                        v-model="scope.row.sheetSize"
                        placeholder="请选择版材尺寸"
                        :disabled="flag"
                      >
                        <!-- @blur="changeWorkBranch(scope.row, scope.$index)"-->
                        <el-option
                          v-for="item in ems_machine_info_size"
                          :key="item.dictValue"
                          :label="item.dictLabel"
                          :value="item.dictValue"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="另行加放"
                  width="85"
                  prop="lxjf"
                  align="center"
                >
                  <!-- :prop="'producePrintList.' + scope.$index + '.lxjf'"
                                            :rules="[
                                                {
                                                    required: true,
                                                    message: '另行加放',
                                                    trigger: 'blur',
                                                },
                                            ]" -->
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        :disabled="flag"
                        type="number"
                        @mousewheel.prevent
                        @blur="changeLossCoefficient(scope.row, scope.$index)"
                        v-model="scope.row.lxjf"
                        placeholder="请输入另行加放"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="印色"
                  width="60"
                  prop="printColour"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="ems_order_print_color"
                      :value="scope.row.printColour"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="印色方式"
                  prop="printColourType"
                  width="120"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="
                        'producePrintList.' + scope.$index + '.printColourType'
                      "
                      :rules="[
                        {
                          required: true,
                          message: '印色方式',
                          trigger: 'change',
                        },
                      ]"
                    >
                      <el-select
                        clearable
                        style="width: 100%"
                        v-model="scope.row.printColourType"
                        placeholder="请选择印色方式"
                        :disabled="flag"
                      >
                        <el-option
                          v-for="item in ems_produce_print_colour_type"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="版材数量"
                  width="85"
                  prop="sheetAmount"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="
                        'producePrintList.' + scope.$index + '.sheetAmount'
                      "
                      :rules="[
                        {
                          required: true,
                          message: '版材数量',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        type="number"
                        @mousewheel.prevent
                        v-model="scope.row.sheetAmount"
                        placeholder="请输入版材数量"
                        :disabled="flag"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  label="活页烤版"
                  prop="hykb"
                  width="120"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'producePrintList.' + scope.$index + '.hykb'"
                    >
                      <!--    :rules="[
                                                {
                                                    required: true,
                                                    message: '活页烤版',
                                                    trigger: 'change',
                                                },
                                            ]"-->
                      <el-select
                        clearable
                        :disabled="flag"
                        style="width: 100%"
                        v-model="scope.row.hykb"
                        placeholder="请选择活页烤版"
                      >
                        <el-option
                          v-for="item in ems_produce_hykb"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                          :disabled="flag"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="工艺"
                  width="120"
                  prop="technologyId"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="
                        'producePrintList.' + scope.$index + '.technologyId'
                      "
                      :rules="[
                        {
                          required: true,
                          message: '工艺',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-select
                        clearable
                        style="width: 100%"
                        v-model="scope.row.technologyId"
                        placeholder="请选择工艺"
                        :disabled="flag"
                      >
                        <el-option
                          v-for="item in technologyList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="白纸裁切"
                  width="120"
                  prop="whitecuttingMachine"
                  align="center"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      @click="
                        handlePrintWorkBranch(
                          scope.row,
                          scope.$index,
                          '5',
                          'whitecuttingMachine'
                        )
                      "
                    >
                      {{ scope.row.whitecuttingMachine }}
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  label="印刷"
                  width="120"
                  prop="printMachine"
                  align="center"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      @click="
                        handlePrintWorkBranch(
                          scope.row,
                          scope.$index,
                          '2',
                          'printMachine'
                        )
                      "
                    >
                      {{ scope.row.printMachine }}
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  label="封面裁切"
                  width="120"
                  prop="covercuttingMachine"
                  align="center"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      @click="
                        handlePrintWorkBranch(
                          scope.row,
                          scope.$index,
                          '6',
                          'covercuttingMachine'
                        )
                      "
                    >
                      {{ scope.row.covercuttingMachine }}
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  label="覆膜"
                  width="100"
                  prop="coveringMachine"
                  align="center"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      @click="
                        handlePrintWorkBranch(
                          scope.row,
                          scope.$index,
                          '7',
                          'coveringMachine'
                        )
                      "
                    >
                      {{ scope.row.coveringMachine }}
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  label="折页"
                  width="120"
                  prop="foldMachine"
                  align="center"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      @click="
                        handlePrintWorkBranch(
                          scope.row,
                          scope.$index,
                          '4',
                          'foldMachine'
                        )
                      "
                    >
                      {{ scope.row.foldMachine }}
                    </el-button>
                  </template>
                </el-table-column>

                <el-table-column
                  label="装订"
                  width="120"
                  prop="bindingMachine"
                  align="center"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      @click="
                        handlePrintWorkBranch(
                          scope.row,
                          scope.$index,
                          '3',
                          'bindingMachine'
                        )
                      "
                    >
                      {{ scope.row.bindingMachine }}
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  label="印刷联版图号"
                  width="120"
                  prop="yslbth"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        :disabled="flag"
                        v-model="scope.row.yslbth"
                        placeholder="请输入印刷联版图号"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="幅宽"
                  width="120"
                  prop="clothWidth"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="品牌"
                  width="120"
                  prop="brand"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_brand"
                      :value="scope.row.brand"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="备注"
                  width="120"
                  prop="remark"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        v-model="scope.row.remark"
                        placeholder="请输入备注"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <!-- //20230325 不从前台分配机器，提交的时候根据印刷工艺自动分配机台 前端不需要展示机台-->
                <!--                                <el-table-column-->
                <!--                                    label="分配机台"-->
                <!--                                    width="120"-->
                <!--                                    prop="machineName"-->
                <!--                                    align="center"-->
                <!--                                >-->
                <!--                                </el-table-column>-->
                <!--                                <el-table-column-->
                <!--                                    label="分配车间"-->
                <!--                                    width="120"-->
                <!--                                    prop="workshopName"-->
                <!--                                    align="center"-->
                <!--                                >-->
                <!--                                </el-table-column>-->
              </el-table>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item title="覆膜管理" disabled name="5">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">覆膜管理</span>
          </template>
          <div class="order-form">
            <el-form
              :model="data"
              ref="produceCoveringListForm"
              :disabled="flag"
              class="data-form"
            >
              <!-- :header-cell-class-name="mustCover" -->
              <el-table
                :data="data.produceCoveringList"
                ref="produceCoveringListRef"
                border
                :row-class-name="tableRowClassName"
              >
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />
                <el-table-column
                  v-if="route.query?.id && !copy"
                  label="覆膜序列号"
                  min-width="120"
                  prop="produceCoveringNo"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="组成"
                  min-width="160"
                  prop="composition"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="ems_order_make_up_fm"
                      :value="scope.row.composition"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="覆膜"
                  min-width="160"
                  prop="covering"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="ems_produce_cover_film"
                      :value="scope.row.covering"
                    />
                  </template>
                </el-table-column>
                <!-- <el-table-column label="用膜" width="120" prop="useCovering" align="center">
                                    <template #default="scope">
                                        <el-form-item>
                                            <el-input v-model="scope.row.useCovering" placeholder="请输入用膜"></el-input>
                                        </el-form-item>
                                    </template>
                                </el-table-column> -->

                <el-table-column
                  label="定量"
                  width="120"
                  prop="weight"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="纸型"
                  width="120"
                  prop="paperType"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_type"
                      :value="scope.row.paperType"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="规格型号"
                  min-width="120"
                  prop="specification"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_specs"
                      :value="scope.row.specification"
                    />
                  </template>
                </el-table-column>
                <!-- <el-table-column label="覆膜尺寸" width="120" prop="coveringSize" align="center">
                                    <template #default="scope">
                                        <el-form-item :prop="'produceCoveringList.' + scope.$index + '.coveringSize'"
                                            :rules="[{ required: true, message: '覆膜尺寸', trigger: 'change' }]">
                                            <el-form-item>
                                                <el-input v-model="scope.row.coveringSize" placeholder="请输入覆膜尺寸"></el-input>
                                            </el-form-item>
                                        </el-form-item>
                                    </template>
                                </el-table-column>
                                <el-table-column label="成品尺寸" width="120" prop="finishSize" align="center">
                                    <template #default="scope">
                                        <el-form-item :prop="'produceCoveringList.' + scope.$index + '.finishSize'"
                                            :rules="[{ required: true, message: '成品尺寸', trigger: 'change' }]">
                                            <el-form-item>
                                                <el-input v-model="scope.row.finishSize" placeholder="请输入成品尺寸"></el-input>
                                            </el-form-item>
                                        </el-form-item>
                                    </template>
                                </el-table-column> -->
                <el-table-column
                  label="令数"
                  width="120"
                  prop="ream"
                  align="center"
                ></el-table-column>
              </el-table>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <orderList
      :visible="orderListOpen"
      @changeUpdate="changeOrderData"
      :orderSelectList="orderSelectList"
      @cancel="
        () => {
          orderListOpen = false;
        }
      "
    ></orderList>
    <SearchPaperCoding
      :useType="'2'"
      :paperType="selectPaperType"
      :visible="paperOpen"
      @changeUpdate="changePaperData"
      @cancel="
        () => {
          paperOpen = false;
        }
      "
    ></SearchPaperCoding>
  </div>
</template>

<script setup>
// 订单内容选过一次不能再选
import { toNumber } from "@/utils/ruoyi";
import SearchPaperCoding from "@/components/SearchPaperCoding";
import { getputratio } from "@/api/basicInfo/workbench.js";
import orderList from "./orderList.vue";
import { getTechnologyList } from "@/api/production/technics.js";
import {
  addProduceOrderList,
  getProduceById,
  getWorkBench,
  getPubNo,
} from "@/api/production/cover";
import { ElMessage } from "element-plus";
import { nextTick, onActivated } from "vue";
import dayjs from "dayjs";

import { v4 as uuidv4 } from "uuid";
import { getList as getDataList } from "@/api/basicInfo/workbench";
import useTagsViewStore from "@/store/modules/tagsView";
import { getDicts } from "@/api/system/dict/data";

const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const {
  cover_workshop,
  ems_produce_new_past,
  // ems_machine_info_size,
  ems_produce_hykb,
  mes_paper_material,
  mes_paper_specs,
  ems_produce_package_require,
  mes_paper_unit,
  ems_produce_print_colour_type,
  ems_produce_color,
  ems_produce_is_new,
  mes_paper_type,
  ems_workshop_subject_type,
  ems_order_make_up,
  ems_order_breed_type,
  ems_order_print_color,
  ems_produce_paper_size,
  ems_produce_cover_film,
  ems_produce_marking,
  ems_machine_info_waste_rate,
  mes_paper_brand,
  produce_text_printer,
  ems_order_make_up_fm,
} = proxy.useDict(
  "cover_workshop",
  "produce_text_printer",
  "mes_paper_brand",
  "ems_machine_info_waste_rate",
  "ems_produce_new_past",
  "mes_paper_unit",
  "ems_produce_package_require",
  "mes_paper_specs",
  "mes_paper_material",
  "ems_produce_hykb",
  // 'ems_machine_info_size',
  "ems_produce_color",
  "ems_produce_print_colour_type",
  "ems_produce_is_new",
  "ems_produce_paper_size",
  "ems_produce_cover_film",
  "ems_produce_marking",
  "mes_paper_type",
  "ems_order_print_color",
  "ems_order_make_up",
  "ems_workshop_subject_type",
  "ems_order_breed_type",
  "ems_order_make_up_fm"
);
const ems_machine_info_size = ref([]);
getDicts("ems_machine_info_size").then((res) => {
  const targetSizes = ["1055*811", "930*721", "1030*790", "1030*800"];
  const sizeSet = new Set(targetSizes);
  ems_machine_info_size.value = res.data.filter((item) =>
    sizeSet.has(item.dictLabel)
  );
  console.log(res);
  console.log(ems_machine_info_size.value);
});
const route = useRoute();
const router = useRouter();
const activeNames = ["1", "2", "3", "4", "5"];
const userRef = ref(null);
const orderSelectList = ref([]);
const orderListOpen = ref(false);
const produceProductListForm = ref(null);
const producePaperListForm = ref(null);
const producePrintListForm = ref(null);
const produceCoveringListForm = ref(null);
const subTip = ref(true);
const flag = ref(false);
const copy = ref(false);
const paperOpen = ref(false);
const selectPid = ref(undefined);
const paperIndex = ref(undefined);
const selectPaperType = ref(undefined);
const stateIndex = ref(undefined);
const technologyList = ref([]); // 工艺
const searchVisible = ref(false);
const selectPrint = ref({});
const selectName = ref("");
const currentIndexJT = ref(0);
const machineType = ref("");
const data = reactive({
  produceProductList: [], // 产品
  producePaperList: [], // 纸张
  producePrintList: [], // 印刷
  produceCoveringList: [], // 覆膜
  producePieceList: [],
  form: {
    isNew: "1", // 默认都是新版
    type: "1",
    workshopId: "10",
    workshopName: "四车间",
  },
  rules: {
    // isNew: [{ required: true, message: '新/旧版不能为空', trigger: 'blur' }],
    // submitDate: [{ required: true, message: "下单日期不能为空", trigger: "blur" },],
    pubNo: [{ required: true, message: "出版编号不能为空", trigger: "blur" }],
    // {
    //     validator: (rule, value, callback) => {
    //         if (form.value.isNew != 2 && subTip.value) {
    //             getProduceOrderList({ pubNo: value, pageNum: 1, pageSize: 9999 }).then(res => {
    //                 if (!route.query.id) {
    //                     if (res.rows.length > 0) {
    //                         callback(new Error('出版编号不能重复'))
    //                     } else {
    //                         callback()
    //                     }
    //                 } else {
    //                     if (route.query.copy) {
    //                         if (res.rows.length > 0) {
    //                             callback(new Error('出版编号不能重复'))
    //                         } else {
    //                             callback()
    //                         }
    //                     } else {
    //                         if (value !== orderNoVal.value) {
    //                             if (res.rows.some(row => row.出版编号 === value)) {
    //                                 callback(new Error('订单编码不能重复'));
    //                             }
    //                         } else {
    //                             callback();
    //                         }
    //                     }
    //                 }
    //             })
    //         } else {
    //             callback()
    //         }
    //     },
    //     trigger: 'blur'
    // },
    // ],
  },
});

const {
  form,
  rules,
  produceProductList,
  producePaperList,
  producePrintList,
  produceCoveringList,
  producePieceList,
} = toRefs(data);
onActivated(() => {
  if (route.query?.id) {
    getProduceById({ pid: route.query.id }).then((res) => {
      Object.assign(form.value, { ...res.data });
      produceProductList.value = res.data.produceProductList;
      producePrintList.value = res.data.producePrintList;
      producePaperList.value = res.data.producePaperList;
      produceCoveringList.value = res.data.produceCoveringList;
      producePieceList.value = res.data.producePieceList;
      if (route.query.info) {
        flag.value = true;
      }
      if (route.query.copy) {
        copy.value = true;
        // getPubNo().then(res => {
        //     form.value.pubNo = 'FM'+res.data
        // })
        // if (form.value.isNew == '1') {
        //     form.value.pubNo = ''
        // }
        producePrintList.value.forEach((item) => {
          item.whitecuttingMachine = undefined;
          item.printMachine = undefined;
          item.covercuttingMachine = undefined;
          item.coveringMachine = undefined;
          item.foldMachine = undefined;
          item.bindingMachine = undefined;
        });
        form.value.isFp = null;
        form.value.urgentNum = undefined;
        form.value.urgentDate = undefined;
        producePieceList.value = [];
      }
    });
  } else {
    // proxy.resetForm('userRef')
    // flag.value = false
    // copy.value = false
    // produceProductList.value = []
    // producePaperList.value = []
    // producePrintList.value = []
    // produceCoveringList.value = []
    // producePieceList.value = []
    // 出版编号
    getPubNo().then((res) => {
      form.value.pubNo = "FM" + res.data;
    });
  }
});

const querySearch = (queryString, cb) => {
  const results = queryString
    ? produce_text_printer.value.filter(createFilter(queryString))
    : produce_text_printer.value;
  cb(results);
};
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};
const handleSelect = (item) => {
  console.log(item);
};
// 印数发生改变
const changePrintAmount = (row, index) => {
  producePrintList.value[index].reamAmount = toNumber(
    Number(row.printAmount) / 1000,
    4
  );
  produceCoveringList.value[0].ream = producePrintList.value[index].reamAmount;
  // produceCoveringList.value.forEach((ele, index) => {
  //     if (ele.orderProductId === row.orderProductId) {
  //         ele.ream = ele.ream ? ele.ream : toNumber(Number(row.printAmount) / 1000, 4)
  //     }
  // })
  changeLossCoefficient(row, index);
};
// 修改出版编号
const changePubNo = (row) => {
  produceProductList.value.forEach((item) => {
    item.pubNo = row;
  });
};

//修改下单日期
const submitDateChange = () => {
  const submitDate = form.value.submitDate;
  const deliverYear = dayjs(submitDate).add(3, "day").format("YYYY");
  const deliverMonth = dayjs(submitDate).add(3, "day").format("MM");
  const deliverDay = dayjs(submitDate).add(3, "day").format("DD");
  form.value.deliverDate = `${deliverYear}-${deliverMonth}-${deliverDay}`;
};

// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  form.value.submitDate = `${year}-${month}-${day}`;
  const deliverYear = dayjs().add(3, "day").format("YYYY");
  const deliverMonth = dayjs().add(3, "day").format("MM");
  const deliverDay = dayjs().add(3, "day").format("DD");
  form.value.deliverDate = `${deliverYear}-${deliverMonth}-${deliverDay}`; // `${year}-${month}-${day}`
  form.value.fileDate = `${year}-${month}-${day}`;
};
getCurrentDateTime();
//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  router.go(-1);
  // tagsViewStore.delView(route);
  // if (route.query.moduleCode == "searchAccess") {
  //   router.push("/storage/searchAccess");
  // } else if (route.query.moduleCode == "waitTakeVersion") {
  //   router.push("/production/waitTakeVersion");
  // } else if (route.query.moduleCode == "takeVersion") {
  //   router.push("/production/takeVersion");
  // } else if (route.query.moduleCode == "searchReportDetail") {
  //   router.push("/production/searchReportDetail");
  // } else {
  //   router.replace({ path: "/production/cover" });
  //   // setTimeout(() => {
  //   //     tagsViewStore.delView(route)
  //   // }, 0)
  // }
};
const must = (obj) => {
  let mustColumns = [];
  if (route.query?.id) {
    if (route.query.copy) {
      mustColumns = [1, 11, 13, 14];
    } else {
      mustColumns = [2, 12, 14, 15];
    }
  } else {
    mustColumns = [1, 11, 13, 14];
  }
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
const mustPaper = (obj) => {
  let mustColumns = [];
  if (route.query?.id) {
    if (route.query.copy) {
      mustColumns = [2, 11];
    } else {
      mustColumns = [3, 12];
    }
  } else {
    mustColumns = [2, 11];
  }
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
const mustPrint = (obj) => {
  let mustColumns = [];
  if (route.query?.id) {
    if (route.query.copy) {
      mustColumns = [8, 11, 12, 14];
    } else {
      mustColumns = [9, 12, 13, 15];
    }
  } else {
    mustColumns = [8, 11, 12, 14];
  }
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
// const mustCover = obj => {
//     let mustColumns = []
//     if (route.query?.id) {
//         if (route.query.copy) {
//             mustColumns = [3, 7, 8]
//         } else {
//             mustColumns = [4, 8, 9]
//         }
//     } else {
//         mustColumns = [3, 7, 8]
//     }
//     if (mustColumns.includes(obj.columnIndex)) {
//         return 'must'
//     }
// }
//  获取工艺
const getTechnologyArr = () => {
  getTechnologyList({ pageNum: 1, pageSize: 100 }).then((res) => {
    technologyList.value = res.rows;
  });
};
getTechnologyArr();
// // 主表订单数量修改
// const changeOrderCount = (row) => {
//     produceProductList.value.forEach(item => {
//         item.produceCount = row
//         changeProduceCount(item)
//     })
// }

//  新增产品信息
const handleAddProduceProduct = () => {
  orderSelectList.value = produceProductList.value;
  orderListOpen.value = true;
};

//20240325 added
const handlePrintWorkBranch = (row, index, type, name) => {
  if (!route.query.info) {
    //  type 机器类型
    selectName.value = name;
    machineType.value = type;
    selectPrint.value = row;
    searchVisible.value = true;
    //  state 2 印刷管理 state 3 贴数管理
    currentIndexJT.value = index;
    stateIndex.value = "2";
  } else {
    if (!name) {
      return;
    }
    const code = row[name].split("/")[3];
    //跳转详情
    getDataList({
      pageNum: 1,
      pageSize: 1,
      machineNo: code,
    }).then((res) => {
      if (res.code == 200) {
        // //跳转到机台
        router.push({
          path: "/basicInfo/workbench/details",
          query: {
            id: res.rows[0].pid,
            info: true,
            moduleCode: "converDetails",
            produceId: route.query.id,
          },
        });
      }
    });
  }
};
// 比较印色
const compareColor = () => {
  let maxLeft = 0;
  let maxRight = 0;
  let maxExpression = "";
  produceProductList.value.forEach((expression) => {
    if (expression.printColor) {
      const [left, right] = findPrintColorToLable(expression.printColor)
        ?.split("+")
        .map(Number);
      if (left > maxLeft) {
        maxLeft = left;
      }
      if (right > maxRight) {
        maxRight = right;
      }
      maxExpression = `${maxLeft}+${maxRight}`;
    }
  });
  return maxExpression;
};
const findPrintColorToLable = (row) => {
  if (row) {
    const resp = ems_order_print_color.value.filter(
      (item) => item.value == row
    );
    return resp[0]?.label;
  }
};
// 获取产品信息
const changeOrderData = (row) => {
  produceProductList.value = row.map((item) => {
    const existingItem = produceProductList.value.find(
      (listItem) => listItem.orderProductId == item.orderProductId
    );
    // 如果存在相同 id 的项，则保留其 value 值
    if (existingItem) {
      return {
        ...existingItem,
        // 是否做版
        // orderProductId:existingItem.pid,
        // productNo: existingItem.productNo,
        // productId: existingItem.productId,
        // newPast: existingItem.newPast,
        // produceCount: existingItem.produceCount,
        // fileNo: existingItem.fileNo,
        // color: existingItem.color,
        // paperSize: existingItem.paperSize,
        // paperType: existingItem.paperType,
        // paperNo: existingItem.paperNo,
        // coverFilm: existingItem.coverFilm,
        // marking: existingItem.marking,
        // lianbanCount: existingItem.lianbanCount,
        // textPrinter: existingItem.textPrinter,
        // customerName: existingItem.customerName,
        // sheet: 1,
      };
    } else {
      return {
        ...item,
        marking:
          item.composition.includes("封面") && item.breed.includes("书")
            ? "1"
            : undefined,
        pubNo: item.pubNo ? item.pubNo : form.value.pubNo,
        sheet: 1, // 印张 封面默认是1
      };
    }
  });
  produceCoveringList.value = [];
  produceCoveringList.value.push({
    ...produceProductList.value[0],
    covering: produceProductList.value[0]?.coverFilm,
  });
  // 印数
  // produceCoveringList.value.ream = [...produceProductList.value[0].covering]
  // produceCoveringList.value.ream = [...produceProductList.value[0].covering]

  // produceCoveringList.value = row.map(item => {
  //     const existingItem = produceCoveringList.value.find(
  //         listItem => listItem.orderProductId == item.orderProductId
  //     )
  //     // 如果存在相同 id 的项，则保留其 value 值
  //     if (existingItem) {
  //         return {
  //             ...existingItem,
  //         }
  //     } else {
  //         return {
  //             ream: toNumber(Number(row.produceCount) / 1000, 4) || 0,
  //             orderProductId: item.orderProductId,
  //             composition: item.composition,
  //             covering: item.coverFilm,
  //         }
  //     }
  // })
  producePrintList.value = row.map((item) => {
    produceProductList.value.forEach((obj) => {
      // 根据覆膜自动生成工艺
      if (obj.coverFilm) {
        item.technologyId = "60541f8f3db44bd39a9535d31353c810";
      } else {
        item.technologyId = "1777261689133518849";
      }
    });
    const existingItem = producePrintList.value.find(
      (listItem) => listItem.orderProductId == item.orderProductId
    );
    // 如果存在相同 id 的项，则保留其 value 值
    if (existingItem) {
      return {
        ...existingItem,
      };
    } else {
      return {
        technologyId: item.technologyId,
        // printSheet 印张
        printId: uuidv4(),
        reamAmount: toNumber((Number(item.produceCount) || 0) / 1000, 4),
        printAmount: Number(item.produceCount) || 0,
        printColour: item.printColor,
        orderProductId: item.orderProductId,
        composition: item.composition,
        sheetSize: item.sheetSize,
        sheet: 1, // 印张 封面默认是1
        lossCoefficient: 0, // 损耗系数
        breed: item.breedType,
        bookName: item.bookName,
        bookNo: item.bookCode,
        sheetAmount: item.printColor ? printColorToLable(item.printColor) : 0, // 印色 *  印张 = 版材数量
      };
    }
  });
  producePrintList.value = producePrintList.value.slice(0, 1);
  orderListOpen.value = false;
  const printColour = compareColor();
  producePrintList.value[0].printColour = findPrintColorToValue(printColour);
  producePrintList.value[0].sheetAmount = findPrintColorToValue(printColour)
    ? printColorToLable(findPrintColorToValue(printColour))
    : 0;
};
const printColorToLable = (row) => {
  const resp = ems_order_print_color.value.filter((item) => item.value == row);
  return eval(resp[0].label);
};
const findPrintColorToValue = (row) => {
  const resp = ems_order_print_color.value.filter((item) => item.label == row);
  return resp[0]?.value;
};
const changePrintColor = (row) => {
  const printColour = compareColor();
  producePrintList.value[0].printColour = findPrintColorToValue(printColour);
  producePrintList.value[0].sheetAmount = producePrintList.value[0].printColour
    ? printColorToLable(producePrintList.value[0].printColour)
    : 0;
  //   produceProductList.value.forEach((item) => {
  //     item.printColor = row.printColor;
  //   });
  //   producePrintList.value.forEach((item) => {
  //     item.printColour = row.printColor;
  //     item.sheetAmount = printColorToLable(row.printColor);
  //   });
};
// 生成覆膜
const changeCoverFilm = (row) => {
  produceProductList.value.forEach((item) => {
    item.coverFilm = row.coverFilm;
  });
  produceCoveringList.value.forEach((item) => {
    if (item.orderProductId === row.orderProductId) {
      item.covering = row.coverFilm;
    }
  });
  producePrintList.value.forEach((item) => {
    if (row.coverFilm) {
      item.technologyId = "60541f8f3db44bd39a9535d31353c810";
    } else {
      item.technologyId = "1777261689133518849";
    }
  });
};

//  生产数量改变 印刷印数重新计算
const changeProduceCount = (row) => {
  //  印数等于 订单数量 (produceCount )/联版数量 (lianbanCount)
  const resp = produceProductList.value.reduce(
    (prev, item) => {
      prev.produceCount += Number(item.produceCount || 0);
      prev.lianbanCount += Number(item.lianbanCount || 0);
      return prev;
    },
    { produceCount: 0, lianbanCount: 0 }
  );
  producePrintList.value[0].printAmount = toNumber(
    Math.ceil(resp.produceCount / (resp.lianbanCount || 1)),
    4
  );
  // 用纸令数
  producePrintList.value[0].reamAmount = toNumber(
    (producePrintList.value[0].printAmount || 0) / 1000,
    4
  );
  //
  produceCoveringList.value[0].ream = producePrintList.value[0].reamAmount;
  // 用纸总令数 用纸令数 +损耗 +另行加放
  // producePrintList.value[0].totalReamAmount = toNumber(
  //     Number(producePrintList.value[0].reamAmount || 0) +
  //         Number(producePrintList.value[0].lossCoefficient || 0) *
  //             Number(producePrintList.value[0].reamAmount || 0) +
  //         Number(producePrintList.value[0].lxjf || 0),
  //     4
  // )
  producePrintList.value[0].totalReamAmount = toNumber(
    ((Number(producePrintList.value[0].printAmount || 0) +
      Number(producePrintList.value[0].lxjf || 0)) /
      1000) *
      (1 + Number(producePrintList.value[0].lossCoefficient || 0)),
    4
  );
  console.log(producePrintList.value[0].totalReamAmount);
  // 纸张 数量
  if (producePaperList.value.length > 0) {
    producePaperList.value[0].reamAmount =
      producePrintList.value[0].totalReamAmount;
  }
};
const changeProduceCountT = (row) => {
  producePrintList.value.forEach((item, index) => {
    if (item.orderProductId === row.orderProductId) {
      item.printAmount = row.produceCount || 0;
      item.reamAmount = toNumber(Number(row.produceCount) / 1000, 4);

      item.lossReam = toNumber(
        Number(item.lossCoefficient || 0) * Number(item.reamAmount || 0),
        4
      );
      item.totalReamAmount = toNumber(
        Number(item.lossCoefficient || 0) * Number(item.reamAmount || 0) +
          Number(item.reamAmount || 0),
        4
      );
      // 汇总纸张的总令数
      //20240325 不从前台分配机器，提交的时候根据印刷工艺自动分配机台
      // if (item.sheetSize) {
      //     changeWorkBranch(item, index)
      // }
    }
  });
  mergeTotal(producePaperList.value, producePrintList.value);

  produceCoveringList.value.forEach((ele, index) => {
    if (ele.orderProductId === row.orderProductId) {
      // ele.ream = ele.ream ? ele.ream : toNumber(Number(row.produceCount) / 1000, 4)
      ele.ream = toNumber(Number(row.produceCount) / 1000, 4);
    }
  });
};

// 选择纸张编码
const openPaperDialog = (row, index) => {
  selectPaperType.value = row.paperType;
  selectPid.value = row.orderProductId;
  paperIndex.value = index;
  paperOpen.value = true;
};

// 选中的纸张编码
const changePaperData = (row) => {
  row.paperInfoId = row.id;
  row.type = "2";
  row.selectPid = selectPid.value;
  row.paperNo = row.code;
  row.specifications = row.specs;
  row.length = row.longWide;
  row.paperName = row.name;
  row.width = row.wide;
  row.unitPrice = row.authorityPrice;
  row.amount = row.quantity;
  row.orderProductId = selectPid.value;
  row.createTime = undefined;
  row.paperName = row.name;
  producePaperList.value = [];
  producePaperList.value.push(row);
  // 产品
  produceProductList.value.forEach((item) => {
    item.paperType = row.paperType;
    item.paperNo = row.code;
    item.paperName = row.name;
  });
  // 印刷
  producePrintList.value[0].paperNo = row.code;
  producePrintList.value[0].weight = row.weight;
  producePrintList.value[0].paperType = row.paperType;
  producePrintList.value[0].printType = row.packageType?.toString(); // 印刷方式
  producePrintList.value[0].clothWidth = row.longWide;
  producePrintList.value[0].brand = row.brand;
  changeLossCoefficient(producePrintList.value[0], 0);
  //覆膜
  produceCoveringList.value[0].weight = row.weight;
  produceCoveringList.value[0].paperType = row.paperType;
  produceCoveringList.value[0].specification = row.specs;
  paperOpen.value = false;
};
const changePaperDataT = (row) => {
  if (!producePaperList.value.some((item) => item.paperNo === row.paperNo)) {
    row.paperInfoId = row.id;
    row.type = "2";
    row.selectPid = selectPid.value;
    row.paperNo = row.code;
    row.specifications = row.specs;
    row.length = row.longWide;
    row.paperName = row.name;
    row.width = row.wide;
    row.unitPrice = row.authorityPrice;
    row.amount = row.quantity;
    row.orderProductId = selectPid.value;
    row.createTime = undefined;
    row.paperName = row.name;
    producePaperList.value.push(row);
    const resp = produceProductList.value.every((item) => !item.paperNo);
    // resp 用没有选中的纸张编码
    if (resp) {
      produceProductList.value.forEach((item) => {
        item.paperType = row.paperType;
        item.paperNo = row.code;
        item.paperName = row.name;
      });
      producePrintList.value.forEach((ele, index) => {
        ele.paperNo = row.code;
        ele.weight = row.weight;
        ele.paperType = row.paperType;
        ele.printType = row.packageType?.toString(); // 印刷方式
        ele.clothWidth = row.longWide;
        ele.brand = row.brand;
        changeLossCoefficient(ele, index);
        //20240325 不从前台分配机器，提交的时候根据印刷工艺自动分配机台
        // if (ele.sheetSize) {
        //     changeWorkBranch(ele, index)
        // }
      });
      produceCoveringList.value.forEach((obj) => {
        obj.weight = row.weight;
        obj.paperType = row.paperType;
        obj.specification = row.specs;
        // obj.ream = row.lingCount
      });
    } else {
      producePrintList.value.forEach((ele, index) => {
        if (ele.orderProductId === row.selectPid) {
          nextTick(() => {
            ele.paperNo = row.code;
            ele.weight = row.weight;
            ele.paperType = row.paperType;
            changeLossCoefficient(ele, index);

            //20240325 不从前台分配机器，提交的时候根据印刷工艺自动分配机台
            // if (ele.sheetSize) {
            //     changeWorkBranch(ele, index)
            // }
          });
        }
      });
      produceCoveringList.value.forEach((obj) => {
        if (obj.orderProductId === row.selectPid) {
          nextTick(() => {
            obj.weight = row.weight;
            obj.paperType = row.paperType;
            obj.specification = row.specs;
            // obj.ream = row.lingCount
          });
        }
      });
    }
  }
  produceProductList.value[paperIndex.value].paperNo = row.code;
  // produceProductList.value[paperIndex.value].paperType = row.paperType
  producePaperList.value = filterArr(
    produceProductList.value,
    producePaperList.value
  );
  nextTick(() => {
    mergeTotal(producePaperList.value, producePrintList.value);
  });
  paperOpen.value = false;
};

function filterArr(list, arr) {
  const uniqueArr = arr.filter((item, index, self) => {
    return (
      self.findIndex((elem) => elem.paperNo === item.paperNo) === index &&
      list.some((elem) => elem.paperNo === item.paperNo)
    );
  });
  return uniqueArr;
}
const tableRowClassName = ({ row, rowIndex }) => {
  // if (chnageState.value.some(item => item.pid === row.orderProductId)) {
  //     return 'success-row';
  // } else {
  //     return '';
  // }
};

// 选择板材尺寸 分配机台 20240325 不从前台分配机器，提交的时候根据印刷工艺自动分配机台
const changeWorkBranch = (row, index) => {
  getWorkBench({ model: 1, size: row.sheetSize }).then((res) => {
    if (res.rows.length > 0) {
      producePrintList.value[index].machineId = res.rows[0].pid;
      producePrintList.value[index].machineName = res.rows[0].machineName;
      producePrintList.value[index].workshopName = res.rows[0].workshopName;
      const rate = ems_machine_info_waste_rate.value.filter(
        (item) => item.value == res.rows[0].wasteRate
      )[0].label;
      producePrintList.value[index].lossCoefficient = Number(rate);
      producePrintList.value[index].lossReam = toNumber(
        Number(producePrintList.value[index].lossCoefficient) *
          Number(row.reamAmount),
        4
      );
      producePrintList.value[index].totalReamAmount = toNumber(
        Number(producePrintList.value[index].lossCoefficient) *
          Number(row.reamAmount) +
          Number(row.reamAmount),
        4
      );

      // 汇总纸张的总令数
      mergeTotal(producePaperList.value, producePrintList.value);
      if (row.printAmount) {
        getputratio({
          machineId: res.rows[0].pid,
          orderNum: row.printAmount,
        }).then((resp) => {
          if (resp || resp == 0) {
            producePrintList.value[index].lxjf = resp;
          }
        });
      }
    } else {
      ElMessage({
        message: "未找到匹配的机台,请去设备/机台管理维护",
        type: "warning",
      });
    }
  });
};
// 损耗系数发生改变
const changeLossCoefficient = (row, index) => {
  // if (!row.lossCoefficient) {
  //     return
  // }
  producePrintList.value[index].lossReam = toNumber(
    Number(producePrintList.value[index].lossCoefficient || 0) *
      Number(row.reamAmount || 0),
    4
  );
  producePrintList.value[0].totalReamAmount = toNumber(
    ((Number(producePrintList.value[0].printAmount || 0) +
      Number(producePrintList.value[0].lxjf || 0)) /
      1000) *
      (1 + Number(producePrintList.value[0].lossCoefficient || 0)),
    4
  );
  // producePrintList.value[index].totalReamAmount = toNumber(
  //     Number(producePrintList.value[index].lossCoefficient || 0) * Number(row.reamAmount || 0) +
  //         Number(row.reamAmount || 0) +
  //         Number(producePrintList.value[index].lxjf || 0),
  //     4
  // )
  // 汇总纸张的总令数
  mergeTotal(producePaperList.value, producePrintList.value);
};

const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除该产品信息及相关信息？").then(function () {
    const isUnique =
      produceProductList.value.filter((item) => item.paperNo === row.paperNo)
        .length == 1;
    if (isUnique) {
      producePaperList.value = producePaperList.value.filter(
        (item) => item.orderProductId !== row.orderProductId
      );
    }
    produceProductList.value = produceProductList.value.filter(
      (item) => item.orderProductId !== row.orderProductId
    );
    producePrintList.value[0].orderProductId =
      produceProductList.value[0].orderProductId;
    // produceCoveringList.value = produceCoveringList.value.filter(
    //   (item) => item.orderProductId !== row.orderProductId
    // );
    changeProduceCount(row);
    changePrintColor(row);

    // 汇总纸张的总令数
    mergeTotal(producePaperList.value, producePrintList.value);
    proxy.$modal.msgSuccess("删除成功");
  });
};

// 累加
const mergeTotal = async (list, arr) => {
  list.forEach((item) => {
    item.reamAmount = 0;
    arr.forEach((obj) => {
      if (item.paperNo == obj.paperNo) {
        //（印数+另行加放）/1000*(1+损耗系数)
        // item.reamAmount += Number(obj.totalReamAmount) || 0
        item.reamAmount += toNumber(
          ((Number(obj.printAmount || 0) + Number(obj.lxjf || 0)) / 1000) *
            (1 + Number(obj.lossCoefficient || 0)),
          4
        );
      }
    });
    // if (item.reamAmount) {
    //     item.reamAmount = toNumber(item.reamAmount, 4)
    //     // item.price = toNumber((Number(item.unitPrice) || 0) * item.reamAmount, 2)
    // }
  });
};

// 清除主键
const clearId = (list, key) => {
  list.forEach((item) => {
    delete item[key];
  });
};
const submitForm = async () => {
  debugger;
  try {
    await userRef.value.validate();
    subTip.value = false;
    await produceProductListForm.value.validate();
    // await producePaperListForm.value.validate()
    await producePrintListForm.value.validate();
    await produceCoveringListForm.value.validate();
    if (route.query?.id) {
      if (copy.value) {
        // 复制
        form.value.status = 1;
        form.value.produceId = undefined;
        producePrintList.value.forEach((item) => {
          item.printId = uuidv4();
        });
        const producePieceList = producePrintList.value.map((item) => {
          return {
            ...item,
            sheet: 1,
          };
        });
        clearId(produceProductList.value, "productId");
        clearId(producePaperList.value, "paperId");
        clearId(producePrintList.value, "printId");
        clearId(produceCoveringList.value, "coveringId");
        // clearId(producePieceList.value, 'pieceId')

        await addProduceOrderList({
          ...form.value,
          processStatus: "1",
          makeStatus: "1",
          isSuspend: "",
          produceProductList: produceProductList.value,
          producePaperList: producePaperList.value,
          producePrintList: producePrintList.value,
          produceCoveringList: produceCoveringList.value,
          producePieceList,
        });
        ElMessage({
          message: "复制成功",
          type: "success",
        });
      } else {
        const producePieceList = producePrintList.value.map((item) => {
          return {
            ...item,
            sheet: 1,
          };
        });
        await addProduceOrderList({
          ...form.value,
          produceProductList: produceProductList.value,
          producePaperList: producePaperList.value,
          producePrintList: producePrintList.value,
          produceCoveringList: produceCoveringList.value,
          producePieceList,
        });
        ElMessage({
          message: "编辑成功",
          type: "success",
        });
      }
      goBack();
    } else {
      // 新增
      const producePieceList = producePrintList.value.map((item) => {
        return {
          ...item,
          sheet: 1,
        };
      });
      form.value.status = 1;
      await addProduceOrderList({
        ...form.value,
        produceProductList: produceProductList.value,
        producePaperList: producePaperList.value,
        producePrintList: producePrintList.value,
        produceCoveringList: produceCoveringList.value,
        producePieceList,
      });
      ElMessage({
        message: "新增成功",
        type: "success",
      });
      goBack();
    }
  } catch (error) {
    if (Object.keys(error)?.join(",").includes(".")) {
      console.log(Object.values(error));
      const errInfoList = Object.values(error);
      console.log(errInfoList);
      const err = [];
      errInfoList.forEach((item) => {
        err.push(item[0].message);
      });
      ElMessage({
        message: `请将${err.join("、")}信息补充完整`,
        type: "warning",
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.footer {
  text-align: center;
}

:deep(.el-pagination) {
  position: unset;
}

.order-form :deep(.el-form-item) {
  margin-bottom: 0px;
}

:deep(.el-table th.must div:before) {
  content: "*";
  color: #ff1818;
}

:deep(.el-table) .success-row {
  background: #dae5f4 !important;
}
</style>
